<template>
  <el-card class="box-card">
    <div slot="header" class="header">
      <span>编辑文章</span>
    </div>

    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-select v-model="ruleForm.author" placeholder="请选择作者">
          <el-option label="张三" value="张三"></el-option>
          <el-option label="李四" value="李四"></el-option>
          <el-option label="王五" value="王五"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即提交</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        title: "",
        author: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "input",
          },
        ],
        author: [{ required: true, message: "请选择作者", trigger: "change" }],
      },
    };
  },
  created() {
    const { id } = this.$route.params;
    const loading = this.$loading({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    this.$store
      .dispatch("article/getArticleAction", id)
      .then((res) => {
        // console.log(res.data);
        this.ruleForm = res.data;
      })
      .finally(() => {
        loading.close();
      });
  },
  methods: {
    submitForm(formName) {
      const { id } = this.$route.params;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store
            .dispatch("article/updateArticleAction", {
              id,
              data: this.ruleForm,
            })
            .then(() => {
              this.$message({
                message: "文章修改成功",
                type: "success",
              });
              this.$router.push({
                name: "articles-detail",
                params: {
                  id,
                },
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
